﻿using System;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;

namespace cludg.Web.Core.RenderHelpers
{
	public static class CheckBoxRenderHelper
	{
		public static MvcHtmlString MyCheckBoxFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, bool>> expression)
		{
			var memberExpression = (MemberExpression)(expression.Body);
			var memberName = memberExpression.Member.Name;
			var mamberValue = expression.Compile().Invoke(html.ViewData.Model);

			var result = new StringBuilder();
			result.Append("<");
			result.Append("input type=\"checkbox\"");
			result.AppendFormat(" id=\"{0}\" ", memberName);
			result.AppendFormat(mamberValue ? " checked=\"checked\" " : "");
			result.AppendFormat(" name=\"{0}\" ", memberName);
			result.Append("value=\"true\" ");
			result.Append("/>");
			result.Append(Environment.NewLine);
			result.Append("<");
			result.Append("input");
			result.AppendFormat(" name=\"{0}\" ", memberName);
			result.Append(" type=\"hidden\" ");
			result.AppendFormat(" value=\"{0}\" ", mamberValue.ToString().ToLowerInvariant());
			result.Append("/>");
			result.Append(Environment.NewLine);

			return MvcHtmlString.Create(result.ToString());
		}
	}
}